<?php
/**
 * Created by PhpStorm.
 * User: maskerj
 * Date: 2017/8/30
 * Time: 下午2:46
 * 用户管理模型
 */
class User_model extends CI_Model{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * @param $username
     * @return boolean 0重复 1不重复
     */
    private function checkUserNameIsUnique($username){
        $row = $this->db->select()->from("users")->where('username',$username)
            ->get()->row_array();
        if(empty($row)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param $userID
     * @param $password
     * @return boolean
     * 更新用户密码
     */
    private function updateUserPassword($userID,$password){
        if ($userID && $password)
        {
            //
            // Here we generate a password salt. This is used, so that in the event of an attacker
            // getting a copy of the users table, they can't brute force the passwords using pre-created
            // hash dictionaries.
            //
            // The salt requires them to have to re-calculate each password possibility for any passowrd
            // they wish to try and break.
            //
            $feed		= "0123456789abcdefghijklmnopqrstuvwxyz";
            $password_salt	= null;

            for ($i=0; $i < 20; $i++)
            {
                $password_salt .= substr($feed, rand(0, strlen($feed)-1), 1);
            }

            // encrypt password with salt
            $password_crypt = sha1("$password_salt"."$password");

            // apply changes to DB.
            $this->db->where('id',$userID);
            $this->db->update("users",[
                'password'      =>  $password_crypt,
                'password_salt' =>  $password_salt
            ]);
            return true;

        }
        return false;
    }

    /**
     * @param $searchData
     * @param $page
     * @param $pageSize
     * @param $sort
     * @param $sortKey
     * @return array
     * 获取用户列表数据
     */
    public function getUserList($searchData,$page,$pageSize,$sort,$sortKey){
        if($searchData == ''){
            $userList = $this->db->select('id,username,realname,contact_email,time,ipaddress')
                ->from("users")
                ->order_by($sortKey,$sort)
                ->limit($pageSize,((int)$page - 1) * $pageSize)
                ->get()->result_array();
            $num = $this->db->select('id,username,realname,contact_email,time,ipaddress')
                ->from("users")
                ->get()->num_rows();
        }else{
            $userList = $this->db->select('id,username,realname,contact_email,time,ipaddress')
                ->from("users")
                ->group_start()
                ->like("username",$searchData)
                ->or_like("realname",$searchData)
                ->group_end()
                ->order_by($sortKey,$sort)
                ->limit($pageSize,((int)$page - 1) * $pageSize)
                ->get()->result_array();

            $num = $this->db->select('id,username,realname,contact_email,time,ipaddress')
                ->from("users")
                ->like("username",$searchData)
                ->or_like("realname",$searchData)
                ->group_end()
                ->get()->num_rows();
        }
        return [
            'users' => $userList,
            'num'   => $num
        ];
    }

    /**
     * @param $username
     * @param $password
     * @param $realname
     * @param $email
     * @return array
     * 添加新用户
     */
    public function addUser($username,$password,$realname,$email){
        //检查用户名是否重复
        $usernameIsUnique = $this->checkUserNameIsUnique($username);
        if($usernameIsUnique){
            //用户名没有重复，插入数据库
            $this->db->trans_begin();
            $this->db->insert("users",[
                'username'  =>  $username,
                'realname'  =>  $realname,
                'contact_email' =>  $email
            ]);
            $uid = $this->db->insert_id();
            //生成用户密码
            $this->updateUserPassword($uid,$password);

            //新增user_options 属性
            $userOptions = [
                [
                    'userid' => $uid,
                    'name'   => 'lang',
                    'value'  => 'en_us'
                ],
                [
                    'userid' => $uid,
                    'name'   => 'dateformat',
                    'value'  => $this->db->select('value')->from('config')->where('name','DATAFORMAT')->get()->row_array()['value']
                ],
                [
                    'userid' => $uid,
                    'name'   => 'shrink_tableoptions',
                    'value'  => 'on'
                ],
                [
                    'userid' => $uid,
                    'name'   => 'debug',
                    'value'  => 'disabled'
                ],
                [
                    'userid' => $uid,
                    'name'   => 'concurrent_logins',
                    'value'  => 'disabled'
                ]
            ];
            $this->db->insert_batch("users_options",$userOptions);

            //插入user_permission
            $this->db->insert("users_permissions",[
                "userid"  => $uid,
                "permid"  => 1
            ]);

            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
                return [
                    'code'  => 0,
                    'msg'   =>  '创建用户失败!'
                ];
            }
            else
            {
                $this->db->trans_commit();
                return [
                    'code'  => 1,
                    'msg'   =>  '创建用户成功!'
                ];
            }

        }else{
            return [
                'code'  => 0,
                'msg'   =>  '用户名已存在!'
            ];
        }
    }


    /**
     * @param $uid
     * @return array
     * 获取用户信息详情
     */
    public function getUserInfo($uid){
        $userOptions = [];
        $hasOptions = [];
        $options = $this->db->select("name,value")->from("users_options")->where('userid',$uid)->get()->result_array();
        if(!empty($options)){
            foreach ($options as $option){
                $hasOptions[$option['name']] = $option['value'];
            }
            $userOptions['option_shrink_tableoptions'] = $hasOptions['shrink_tableoptions'];
            $userOptions['option_concurrent_logins']   = $hasOptions['concurrent_logins'];
        }else{
            $userOptions['option_shrink_tableoptions'] = NULL;
            $userOptions['option_concurrent_logins']   = NULL;
        }

        $user = $this->db->select("id,username,realname,contact_email,time,ipaddress")
            ->from("users")
            ->where("id",$uid)
            ->get()->row_array();

        $optionLang = $this->db->select("name as id,name as label")
            ->from("language_avaliable")
            ->order_by("name")
            ->get()->result_array();
        $option_dateformat = ["yyyy-mm-dd", "mm-dd-yyyy", "dd-mm-yyyy"];

        $userOptions['user'] = $user;
        $userOptions['optionLang'] = $optionLang;
        $userOptions['dateformat'] = $option_dateformat;

        return $userOptions;
    }

    /**
     * @param $data
     * @return array
     * 更新用户信息
     */
    public function updateUser($data){
        $uid = $data['uid'];
        //判断用户是否要更新密码
        if($data['password'] != ''){
            $this->updateUserPassword($uid,$data['password']);
        }
        $this->db->trans_begin();
        //更新用户信息
        $this->db->where('id',$uid);
        $this->db->update('users',[
            'username'  =>  $data['username'],
            'realname'  =>  $data['realname'],
            'contact_email' => $data['contact_email']
        ]);

        //更新 user_options，先删除再插入
        $this->db->where('id',$uid);
        $this->db->delete('users_options');

        $userOptions = [
            [
                'userid' => $uid,
                'name'   => 'lang',
                'value'  => $data['option_lang']
            ],
            [
                'userid' => $uid,
                'name'   => 'dateformat',
                'value'  => $data['option_dateformat']
            ],
            [
                'userid' => $uid,
                'name'   => 'shrink_tableoptions',
                'value'  => $data['option_shrink_tableoptions']
            ],
            [
                'userid' => $uid,
                'name'   => 'debug',
                'value'  => $data['option_debug']
            ],
            [
                'userid' => $uid,
                'name'   => 'concurrent_logins',
                'value'  => $data['option_concurrent_logins']
            ]
        ];
        $this->db->insert_batch("users_options",$userOptions);

        //更新 config
        $this->db->where('name','PROCMAIL_UPDATE_STATUS');
        $this->db->update('config',[
            'value'  =>  'update_required'
        ]);

        //删除session
        $this->db->where('userid',$uid);
        $this->db->delete('users_sessions');

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return [
                'code'  => 0,
                'msg'   =>  '更新用户失败!'
            ];
        }
        else
        {
            $this->db->trans_commit();
            return [
                'code'  => 1,
                'msg'   =>  '更新用户成功!'
            ];
        }
    }

    /**
     * @param $uid
     * @return array
     * 获取用户权限信息
     */
    public function getUserPer($uid){
        $userPer = [];
        //获取所有权限
        $allPer = $this->db->select()->from('permissions')
            ->order_by("value='disabled' DESC, value='admin' DESC, value")
            ->get()->result_array();
        //判断该用户是否用户此权限
        foreach ($allPer as $per){
            $hasPer = $this->db->select('id')->from('users_permissions')
                ->where('userid',$uid)
                ->where('permid',$per['id'])
                ->get()->result_array();
            if(!empty($hasPer)){
                array_push($userPer,[
                    'key'   =>  $per['value'],
                    'description' => $per['description'],
                    'value' =>  'on'
                ]);
            }else{
                array_push($userPer,[
                    'key'   =>  $per['value'],
                    'description' => $per['description'],
                    'value' =>  'off'
                ]);
            }
        }
        return [
            'uid'       => $uid,
            'userPer'   => $userPer
        ];
    }

    /**
     * @param $per
     * @param $uid
     * @return array
     * 更新用户权限
     */
    public function updateUserPer($pers,$uid){
        $allPer = $this->db->select()->from('permissions')
            ->order_by("value='disabled' DESC, value='admin' DESC, value")
            ->get()->result_array();
        $permissions = [];
        foreach ($allPer as $one){
            $permissions[$one['value']] = $pers[$one['value']];
        }
        //检查用户是否存在
        $hasUser = $this->db->select('id')->from('users')
            ->where('id',$uid)
            ->get()->row_array();
        if(empty($hasUser)){
            return [
                'code'  =>  0,
                'msg'   =>  '用户id错误！'
            ];
        }
        //更新用户权限
        $this->db->trans_begin();
        foreach ($allPer as $per){
            $userPer = $this->db->select('id')->from('users_permissions')
                ->where('userid',$uid)
                ->where('permid',$per['id'])
                ->get()->row_array();
            if(!empty($userPer)){
                //判断更新值是否为off，off则删除对应关系，on不变
                if($permissions[$per['value']] == 'off'){
                    $this->db->where('userid',$uid);
                    $this->db->where('permid',$per['id']);
                    $this->db->delete('users_permissions');
                }
            }else{
                if($permissions[$per['value']] == 'on'){
                    //不存在这个权限则新加一个对应关系
                    $this->db->insert('users_permissions',[
                        'userid' => $uid,
                        'permid' => $per['id']
                    ]);
                }
            }
        }

        if ($this->db->trans_status() === FALSE)
        {
            $this->db->trans_rollback();
            return [
                'code'  => 0,
                'msg'   =>  '更新失败!'
            ];
        }
        else
        {
            $this->db->trans_commit();
            return [
                'code'  => 1,
                'msg'   =>  '更新成功!'
            ];
        }
    }

    /**
     * @param $uid
     * @return array
     * 删除用户
     */
    public function delUser($uid){
        //检查用户是否存在
        $hasUser = $this->db->select('id')->from('users')
            ->where('id',$uid)
            ->get()->row_array();
        if(empty($hasUser)){
            return [
                'code'  =>  0,
                'msg'   =>  '用户id不存在!'
            ];
        }else{
            //删除相关的表数据
            $this->db->trans_begin();

            $this->db->where('id',$uid);
            $this->db->delete('users');

            $this->db->where('userid',$uid);
            $this->db->delete('users_options');

            $this->db->where('userid',$uid);
            $this->db->delete('users_permissions');

            if ($this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
                return [
                    'code'  => 0,
                    'msg'   =>  '删除失败!'
                ];
            }
            else
            {
                $this->db->trans_commit();
                return [
                    'code'  => 1,
                    'msg'   =>  '删除成功!'
                ];
            }
        }
    }




}